package com.qq.websocket;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qq.bean.Chatrecord;
import com.qq.bean.Friend;
import com.qq.bean.FriendshipVO;
import com.qq.service.FriendshipService;
import com.qq.service.impl.FriendshipServiceImpl;

@ServerEndpoint(value = "/InsertFriend/{account}")
public class InsertFriend {
	private static final Map<String,Session> userSession = new ConcurrentHashMap<String, Session>();
	private static final Set<Session> sessionss = Collections.synchronizedSet(new HashSet<>());//所有聊天管道
	private static final ObjectMapper om = new ObjectMapper();
	private FriendshipService fs = new FriendshipServiceImpl();
	
	@OnOpen
    public void onOpen(Session session,@PathParam("account")String account) {
		
       System.out.println("连接创立");
       sessionss.add(session);
       userSession.put(account, session);
	   System.out.println("当前存在的用户和通道:"+sessionss);
    }


    @OnClose
    public void onClose() {
    	System.out.println("连接关闭");
    	System.out.println(sessionss+"关闭了");
    	sessionss.remove(sessionss);
		Set<String> keys = userSession.keySet();
		for(String key:keys) {
			if(userSession.get(key) == sessionss) {
				userSession.remove(key);
			}
		}
    }
   
    public Session getSession(String acount) {
    	return userSession.get(acount);
    }
  
    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
    	System.out.println("接受信息"+message);
    	//1.把用户消息存入到数;据库
    	FriendshipVO friendshipVO  = om.readValue(message, FriendshipVO.class);
    	//删除修改状态
    	String myaccount = friendshipVO.getMyaccount();
    	String friendaccount = friendshipVO.getFriendaccount();
    	
    	int i = fs.insertFriendByAccount(myaccount, friendaccount);
    	
    	//判断好友在不在线
    	Session friendSession = getSession(friendaccount);
    	//把消息推送给好友
    	if(friendSession != null) {
    		broadCastMsg(friendSession, friendshipVO);
    	}
    	//消息推送给自己，用于在页面回显示
    	broadCastMsg(session,friendshipVO);
    }
    

    //推送消息给 用户
    public static void  broadCastMsg(Session session,FriendshipVO friendshipVO) throws JsonParseException, JsonMappingException, IOException {
	
		session.getBasicRemote().sendText(om.writeValueAsString(friendshipVO));
		
	 } 



    
    @OnError
    public void onError(Throwable t) throws Throwable {
    	t.printStackTrace();
    	System.out.println("系统异常");
    }
}
